local class = reload("class")
local order = require("order")
local cmsgpack = require("cmsgpack")
local bagManager = require("bagManager")

---@class bidderManager @拍卖行管理
local this = class()

function this:ctor(rdb, dbs)
    self._rdb = rdb
    self._dbs = dbs
    self._fin = false
    self._map = {}
    self._sum = {}
    self.order = order(cgzSid)
    self.bag = bagManager(rdb, dbs)
end

function this:launch()
    self:readBidder({
        order = 0,
        limit = 1000,
    })
end

function this:readBidder(arg)
    local fes =
    "`orderid`,`cdkey`,`type`,`id`,`count`,`price`,`info`,from_unixtime(`ctime`) as `ctime`,from_unixtime(`dtime`) as `dtime`,`aid`"
    local fmt = [[
    select %s
    from tbl_bidder
    where orderid > %d limit %d;]]
    local sql = string.format(fmt, fes, arg.order, arg.limit)
    self._dbs:fetch():select(sql)(self.waitBidder, arg)
end

function this:waitBidder(arg, rows)
    for i, row in ipairs(rows) do
        if row.info then
            row.info = cmsgpack.unpack(row.info)
        end
        self._map[row.orderid] = row
        arg.order = math.max(arg.order, row.orderid)

        ---上架商品数量统计
        local cnt = self._sum[row.cdkey] or 0
        cnt = cnt + 1
        self._sum[row.cdkey] = cnt
    end

    local len = #rows
    if len >= arg.limit then
        ---继续加载
        self:readBidder(arg)
        return
    end

    self._fin = true
end

---出售
function this:sale(cdkey, grid, tcost, price, count)
    ---检查上架限制
    local old = self._sum[cdkey] or 0
    if old > 10 then
        return false, "上架数量已达上限"
    end


    
end

---购买
function this:buy(cdkey, order, count)
end

return this
